#include "head.h"

//服务器gets处理逻辑
bool my_gets(sendMsg msg,client_status *user,int net_fd)
{
    //1接收文件名和文件长度
    int file_name_len;
    char file_name[1000];
    recv(net_fd,&file_name_len,sizeof(int),MSG_WAITALL);
    recv(net_fd,file_name,file_name_len,MSG_WAITALL);
    
    //2.getcwd
    char path[1000]={0};
   // getcwd(path,sizeof(path));
    strcpy(path,user->root_path);
   // strcat(path,"/");
   // strcat(path,user->user_name);
    //strcat(path,user->path);
    strcat(path,user->path_last);
    printf("path1:%s\n",path);
    strcat(path,"/");
    strcat(path,file_name);
    printf("!!!path2:%s\n",path);
     
    int file_fd = open(path, O_RDWR);
    ERROR_CHECK(file_fd,-1,"file_fd");
    
    //接收偏移量
    off_t offset;
    recv(net_fd,&offset,sizeof(int),MSG_WAITALL);

    //获取文件大小并且发给客户端
    struct stat st;
    fstat(file_fd,&st);
    send(net_fd,&st.st_size,sizeof(st.st_size),MSG_NOSIGNAL);

    // 使用 sendfile 从偏移量继续发送文件内容
    ssize_t sent_bytes;
    while (offset < st.st_size) {
        sent_bytes = sendfile(net_fd, file_fd, &offset, st.st_size - offset);
        if (sent_bytes <= 0) {
            if (errno == EINTR || errno == EAGAIN) {
                continue; // 如果发生了中断或资源临时不可用，继续发送
            } else {
                perror("sendfile");
                close(file_fd);
                return false;
            }
        }
        printf("sent_bytes:%ld\n",sent_bytes);
        offset += sent_bytes;
    }


    close(file_fd);
    return true;
}
